﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.IO;
using Commons = NougakudoCompanion.Commons;

namespace AdminWeb.Models
{
    public class ControllerLog
    {
        Commons.Runtime runtime;

        List<string> instances;
        Dictionary<string, string[]> logs;

        public ControllerLog(Commons.Runtime runtime)
        {
            this.runtime = runtime;
            instances = Helper.GetInstanceIDs(runtime);
            GetLogData();
        }

        public List<string> Instances { get { return instances; } }
        public Dictionary<string, string[]> Logs { get { return logs; } }

        void GetLogData()
        {
            logs = new Dictionary<string,string[]>();
            foreach (var instance in instances)
            {
                string file = "";
                string logName = "NougakuDoController.txt";
                if (instance == runtime.Environment.RoleInstanceID)
                {
                    file = Path.Combine(runtime.Environment.RuntimeFolder, logName);
                }
                else
                {
                    file = Helper.GetDataFromBlob(runtime, logName, instance);
                }
                logs[instance] = GetData(file);
            }
        }

        string[] GetData(string file)
        {
            string[] logs = new string[]{};
            try
            {
                if (File.Exists(file))
                    logs = File.ReadAllLines(file);
            }
            catch
            {
            }

            return logs.Reverse().ToArray();

        }

    }
}